using DocumentCreationSystem.Models.MCP;

namespace DocumentCreationSystem.Services.MCP
{
    /// <summary>
    /// MCP客户端接口
    /// </summary>
    public interface IMCPClient : IDisposable
    {
        /// <summary>
        /// 连接状态
        /// </summary>
        bool IsConnected { get; }

        /// <summary>
        /// 服务器信息
        /// </summary>
        MCPServerInfo? ServerInfo { get; }

        /// <summary>
        /// 连接到MCP服务器
        /// </summary>
        Task<bool> ConnectAsync(string serverPath, string[] args, CancellationToken cancellationToken = default);

        /// <summary>
        /// 断开连接
        /// </summary>
        Task DisconnectAsync();

        /// <summary>
        /// 初始化连接
        /// </summary>
        Task<MCPInitializeResponse> InitializeAsync(MCPInitializeRequest request, CancellationToken cancellationToken = default);

        /// <summary>
        /// 发送初始化完成通知
        /// </summary>
        Task SendInitializedAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// 获取可用工具列表
        /// </summary>
        Task<List<MCPTool>> ListToolsAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// 调用工具
        /// </summary>
        Task<MCPToolCallResult> CallToolAsync(MCPToolCallRequest request, CancellationToken cancellationToken = default);

        /// <summary>
        /// 获取可用资源列表
        /// </summary>
        Task<List<MCPResource>> ListResourcesAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// 读取资源内容
        /// </summary>
        Task<List<MCPContent>> ReadResourceAsync(string uri, CancellationToken cancellationToken = default);

        /// <summary>
        /// 获取可用提示模板列表
        /// </summary>
        Task<List<MCPPromptTemplate>> ListPromptsAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// 获取提示模板
        /// </summary>
        Task<MCPContent> GetPromptAsync(string name, Dictionary<string, string>? arguments = null, CancellationToken cancellationToken = default);

        /// <summary>
        /// 发送ping请求
        /// </summary>
        Task<bool> PingAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// 连接状态变化事件
        /// </summary>
        event EventHandler<bool>? ConnectionStateChanged;

        /// <summary>
        /// 错误事件
        /// </summary>
        event EventHandler<Exception>? ErrorOccurred;

        /// <summary>
        /// 日志事件
        /// </summary>
        event EventHandler<string>? LogReceived;
    }

    /// <summary>
    /// MCP服务器配置
    /// </summary>
    public class MCPServerConfig
    {
        /// <summary>
        /// 服务器名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 服务器描述
        /// </summary>
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 服务器可执行文件路径
        /// </summary>
        public string ServerPath { get; set; } = string.Empty;

        /// <summary>
        /// 启动参数
        /// </summary>
        public string[] Args { get; set; } = Array.Empty<string>();

        /// <summary>
        /// 环境变量
        /// </summary>
        public Dictionary<string, string> Environment { get; set; } = new();

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// 连接超时时间（毫秒）
        /// </summary>
        public int TimeoutMs { get; set; } = 30000;

        /// <summary>
        /// 自动重连
        /// </summary>
        public bool AutoReconnect { get; set; } = true;

        /// <summary>
        /// 最大重连次数
        /// </summary>
        public int MaxReconnectAttempts { get; set; } = 3;

        /// <summary>
        /// 重连间隔（毫秒）
        /// </summary>
        public int ReconnectIntervalMs { get; set; } = 5000;
    }

    /// <summary>
    /// MCP连接状态
    /// </summary>
    public enum MCPConnectionState
    {
        Disconnected,
        Connecting,
        Connected,
        Initializing,
        Ready,
        Error
    }

    /// <summary>
    /// MCP客户端事件参数
    /// </summary>
    public class MCPClientEventArgs : EventArgs
    {
        public string Message { get; set; } = string.Empty;
        public Exception? Exception { get; set; }
        public object? Data { get; set; }
    }

    /// <summary>
    /// MCP工具调用上下文
    /// </summary>
    public class MCPToolCallContext
    {
        /// <summary>
        /// 调用ID
        /// </summary>
        public string CallId { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 工具名称
        /// </summary>
        public string ToolName { get; set; } = string.Empty;

        /// <summary>
        /// 调用参数
        /// </summary>
        public Dictionary<string, object> Arguments { get; set; } = new();

        /// <summary>
        /// 调用时间
        /// </summary>
        public DateTime CallTime { get; set; } = DateTime.Now;

        /// <summary>
        /// 超时时间
        /// </summary>
        public TimeSpan Timeout { get; set; } = TimeSpan.FromMinutes(5);

        /// <summary>
        /// 取消令牌
        /// </summary>
        public CancellationToken CancellationToken { get; set; }

        /// <summary>
        /// 用户上下文
        /// </summary>
        public Dictionary<string, object> UserContext { get; set; } = new();
    }

    /// <summary>
    /// MCP客户端统计信息
    /// </summary>
    public class MCPClientStatistics
    {
        /// <summary>
        /// 连接次数
        /// </summary>
        public int ConnectionCount { get; set; }

        /// <summary>
        /// 成功连接次数
        /// </summary>
        public int SuccessfulConnections { get; set; }

        /// <summary>
        /// 工具调用次数
        /// </summary>
        public int ToolCallCount { get; set; }

        /// <summary>
        /// 成功工具调用次数
        /// </summary>
        public int SuccessfulToolCalls { get; set; }

        /// <summary>
        /// 平均响应时间（毫秒）
        /// </summary>
        public double AverageResponseTimeMs { get; set; }

        /// <summary>
        /// 错误次数
        /// </summary>
        public int ErrorCount { get; set; }

        /// <summary>
        /// 最后连接时间
        /// </summary>
        public DateTime? LastConnectionTime { get; set; }

        /// <summary>
        /// 最后错误时间
        /// </summary>
        public DateTime? LastErrorTime { get; set; }

        /// <summary>
        /// 最后错误信息
        /// </summary>
        public string? LastErrorMessage { get; set; }

        /// <summary>
        /// 连接成功率
        /// </summary>
        public double ConnectionSuccessRate => ConnectionCount > 0 ? (double)SuccessfulConnections / ConnectionCount : 0;

        /// <summary>
        /// 工具调用成功率
        /// </summary>
        public double ToolCallSuccessRate => ToolCallCount > 0 ? (double)SuccessfulToolCalls / ToolCallCount : 0;
    }
}
